<?php
namespace Home\Controller;

/**
 * IndexController
 */
class IndexController extends CommonController {
    public function index() {
        $vote = M('Vote')->order('sort asc, id desc')->select();
        $totalCount = M('Vote')->sum('count');
        
        foreach ($vote as $k => $v) {
            $percent = round(($vote[$k]['count']/$totalCount)*100);
            $vote[$k]['percent'] = $percent;
        }

        $this->assign('vote',$vote);
        $this->display();
    }
    
    public function submit() {
        $ip = $_SERVER['REMOTE_ADDR'];
        $ipWhere['ip'] = $ip;
        $result = M('Ip')->where($ipWhere)->find();
        if ($result) {  //当前客户端IP已投票
            return $this->errorReturn('亲，你已经投过票了，感谢您的支持！');
        } else {
            $voteId = $_POST['voteId'];
            $where['id'] = array(in, $voteId); 
            $state = M('Vote')->where($where)->setInc('count');
            $ipData['ip'] = $ip;
            $ipData['created_at'] = $ipData['updated_at'] = time(); 
            $ipState = M('Ip')->add($ipData);
            
            if ($state && $ipState) {
                $vote = M('Vote')->order('sort asc, id desc')->select();
                $totalCount = M('Vote')->sum('count');
                
                foreach ($vote as $k => $v) {
                    $percent = round(($vote[$k]['count']/$totalCount)*100);
                    $vote[$k]['percent'] = $percent;
                }
                
                $data['vote'] = $vote;
                $data['status'] = true;
                $data['ip'] = $ip;
                $data['info'] = '投票成功！';
                $this->ajaxReturn($data);
            } else {
                return $this->errorReturn('投票失败！');
            }
        }  
    }
    
    public function submit2() {
        $data['result'] = $_POST['voteId'];
        $data['mobile'] = $_POST['mobile'];
        $data['weixin'] = $_POST['weixin'];
        $data['qq'] = $_POST['qq'];
        $data['created_at'] = $data['updated_at'] = time();  
        
        $state = M('Feedback')->add($data);
        
        if ($state) {
            return $this->successReturn('提交成功！');
        } else {
            return $this->errorReturn('提交失败！');
        }
    }
}
